<template>
  <a-form
    ref="formRef"
    :model="formData"
    class="form"
    :label-col-props="{ span: 6 }"
    :wrapper-col-props="{ span: 18 }"
  >
    <a-form-item
      field="employeeInfo"
      label="select employee_info data"
      :rules="[{ required: true, message: '请选择一个选项' }]"
    >
      <a-select
        v-model="formData.employeeInfo"
        placeholder="select employee_info data"
      >
        <a-option
          v-for="option in employeeInfoOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-option>
      </a-select>
    </a-form-item>

    <a-form-item
      field="timesheet"
      label="select timesheet data"
      :rules="[{ required: true, message: '请选择一个选项' }]"
    >
      <a-select
        v-model="formData.timesheet"
        placeholder="select timesheet data"
      >
        <a-option
          v-for="option in timesheetOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-option>
      </a-select>
    </a-form-item>

    <a-form-item
      field="payroll"
      label="select payroll data"
      :rules="[{ required: true, message: '请选择一个选项' }]"
    >
      <a-select v-model="formData.payroll" placeholder="select payroll data">
        <a-option
          v-for="option in payrollOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-option>
      </a-select>
    </a-form-item>

    <a-form-item>
      <a-button type="primary" @click="onNextClick">
        {{ $t('Start Process') }}
      </a-button>
    </a-form-item>

    <RulesPreset @update:selectedRules="handleSelectedRule" />
  </a-form>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import axios from 'axios';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { BaseInfoModel } from '@/api/form';
  import RulesPreset from './rules-preset.vue';
  import baseUrl from '../../../../config';


  const emits = defineEmits(['changeStep']);
  const formRef = ref<FormInstance>();
  const formData = ref({
    employeeInfo: null,
    timesheet: null,
    payroll: null,
  });
  const selectedRule = ref(null);

  const employeeInfoOptions = ref([]);
  const timesheetOptions = ref([]);
  const payrollOptions = ref([]);

  const fetchData = async () => {
    try {
      const response = await axios.get('http://101.35.43.81:8111/api/files');
      response.data.forEach((item) => {
        const option = {
          value: item.id,
          label: item.file_name + item.id || `ID: ${item.id}`,
        };
        // console.log(item)

        switch (item.file_type) {
          case 'employee_info':
            employeeInfoOptions.value.push(option);
            break;
          case 'timesheet':
            timesheetOptions.value.push(option);
            break;
          case 'payroll':
            payrollOptions.value.push(option);
            break;
          default:
            console.error(`Unhandled file type: ${item.file_type}`);
            break;
        }

        if (employeeInfoOptions.value.length > 0) {
          formData.value.employeeInfo =
            employeeInfoOptions.value[
              employeeInfoOptions.value.length - 1
            ].value;
        }
        if (timesheetOptions.value.length > 0) {
          formData.value.timesheet =
            timesheetOptions.value[timesheetOptions.value.length - 1].value;
        }
        if (payrollOptions.value.length > 0) {
          formData.value.payroll =
            payrollOptions.value[payrollOptions.value.length - 1].value;
        }
      });
    } catch (error) {
      console.error('Failed to fetch data:', error);
    }
  };

  onMounted(fetchData);

  function handleSelectedRule(rule) {
    selectedRule.value = rule;
    console.log('Selected rule:', selectedRule.value);
  }

  const onNextClick = async () => {
    console.log('所选规则1');
    console.log(selectedRule.value);

    console.log('所选文件1');
    console.log(formData.value);
    let logInfo = '';
    let taskId = null;
    const res = await formRef.value?.validate();
    if (!res) {
      try {
        const response = await axios.post(
          `${baseUrl}/api/calculate`,
          {
            file_id_list: Object.values(formData.value),
            industry: '某行业', // 如果有这个字段，你需要替换为实际值
            rule_id_list: selectedRule.value,
          },
          {
            headers: {
              'accept': 'application/json',
              'authorization': 'Basic YWRtaW46YWRtaW5AMTIz',
              'Content-Type': 'application/json',
              'X-CSRFToken':
                'pQmYuJCOVKskmlaRAHi3V7XVZJvmd2tFhHS3O4CL7BgjyURjHEcRlZ2mPhcUBBbA',
            },
          }
        );

        console.log('API response:', response.data.log);
        logInfo = response.data.log;
        taskId = response.data.task_id;
      } catch (error) {
        console.error('API call error:', error);
      }

      emits('changeStep', 'forward', { ...formData.value, logInfo, taskId });
    }
  };
</script>

<style scoped lang="less">
  .container {
    padding: 20px;
  }

  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 64px 0;
    background-color: var(--color-bg-2);
  }

  .steps {
    margin-bottom: 36px;
  }

  .form {
    width: 1000px;
  }

  .form-content {
    padding: 8px 50px 0 30px;
  }
</style>
